package com.fm.common.net.baseCoroutine.exception

import com.blankj.utilcode.util.LogUtils
import com.fm.common.net.baseCoroutine.uiScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout

/**
 * @CreateData:     2020/12/22
 * @Author:         lyy
 * @Description:    Deferred 扩展
 */
infix fun <T> Deferred<T>.then(block: (T) -> Unit) = uiScope().launch {

    block(this@then.await())
}

infix fun <T, R> Deferred<T>.thenAsync(block: (T) -> R) = uiScope().async {

    block(this@thenAsync.await())
}

//infix fun <T> Deferred<T>.lifeRecycle(fifecycle: Lifecycle): Deferred<T> {
//    LifeRecycleControl(fifecycle).bind(this)
//    return this
//}

/**
 * 如果遇到超时或者异常，则返回null。
 */
suspend fun <T> Deferred<T>.awaitOrNull(timeout: Long = 0L) = try {

    if (timeout > 0) {

        withTimeout(timeout) {

            this@awaitOrNull.await()
        }

    } else {

        this.await()
    }
} catch (e: Exception) {

    LogUtils.e("Deferred", e.message)
    null
}